package com.faithnmn.learnenglishbc.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.faithnmn.learnenglishbc.model.Transcript;

public class TranscriptUtil {
	public static ArrayList<Transcript> getTranscripts(JSONObject transcript){
		ArrayList<Transcript> res = new ArrayList<Transcript>();
		if(transcript != null && transcript.has("script")){
			try
			{
			JSONObject scriptJson = transcript.getJSONObject("script");
			JSONArray arr = scriptJson.names();
			if(arr != null){
				ArrayList<String> keys = new  ArrayList<String>();
				for(int i=0;i<arr.length();i++){
						keys.add(arr.get(i).toString());
				}
				for(int i=0;i<keys.size();i++){
					Transcript script = new Transcript();
					script.startMilisecond = Long.parseLong(keys.get(i));
					script.content = scriptJson.getString(keys.get(i));
					res.add(script);
				}
			}
			}catch(JSONException ex){
				ex.printStackTrace();
			}
		}
		Collections.sort(res, FruitNameComparator);
		return res;
	}
	
	public static Comparator<Transcript> FruitNameComparator = new Comparator<Transcript>() {

		public int compare(Transcript scriptStart1, Transcript scriptStart2) {
			long start1 = scriptStart1.startMilisecond;
			long start2 = scriptStart2.startMilisecond;
			if(start1 > start2){
				return 1;
			}else if(start1 < start2){
				return -1;
			}else return 0;
		}

	};
}
